package com.zhaolang.qogir.ui.manage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.zhaolang.qogir.R;
import com.zhaolang.qogir.bean.ManageProductDetails;
import com.zhaolang.qogir.bean.ProductBean;
import com.zhaolang.qogir.bean.ProductClassBean;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.ReqFactory;
import com.zhaolang.qogir.domain.WaresManage;
import com.zhaolang.qogir.model.FirstClassItem;
import com.zhaolang.qogir.model.SecondClassItem;
import com.zhaolang.qogir.ui.BaseActivity;
import com.zhaolang.qogir.ui.ContextState;
import com.zhaolang.qogir.ui.TitleView;
import com.zhaolang.qogir.ui.adapter.manage.FirstClassAdapter;
import com.zhaolang.qogir.ui.adapter.manage.ListDropDownAdapter;
import com.zhaolang.qogir.ui.adapter.manage.ManageProductDetailsAdapter;
import com.zhaolang.qogir.ui.adapter.manage.SecondClassAdapter;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.ScreenUtils;
import com.zhaolang.qogir.util.Slog;
import com.zhaolang.qogir.util.ToastUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ActivityManageShopClassify extends BaseActivity implements View.OnClickListener {

    private TextView mainTab1TV;
    private static final String PRODUCT_IS_SALE = "1";
    /**
     * 左侧一级分类的数据
     */
    private List<FirstClassItem> firstList;
    /**
     * 右侧二级分类的数据
     */
    private List<ManageProductDetails> secondList;

    /**
     * 使用PopupWindow显示一级分类和二级分类
     */
    private PopupWindow popupWindow;

    /**
     * 左侧和右侧两个ListView
     */
    private ListView leftLV, rightLV;
    //弹出PopupWindow时背景变暗
    private View darkView;

    //弹出PopupWindow时，背景变暗的动画
    private Animation animIn, animOut;

    private TitleView mTitle;
    private LinearLayout manage_shop_rel;
    private LinearLayout manage_btn_add, manage_btn_class, manage_btn_sort;
    /* list all product */
    private List<ProductBean> proList;
    /* list all product class */
    private List<ProductClassBean> classList;
    private WaresManage waresManage;
    private ManageProductDetailsAdapter secondAdapter;
    private FirstClassAdapter firstAdapter;
    private Context mContext;

    private OkHttpClient okHttpClient = new OkHttpClient();
    private final static int BASE = 101;
    private final static int MSG_LOAD_PRODUCT_CLASS = BASE + 1;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_PRODUCT_CLASS:
                    notifyUi();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private BaseCall<WaresManage.ListProductBeanReq> mProductCallback = new BaseCall<WaresManage.ListProductBeanReq>() {
        @Override
        public void call(WaresManage.ListProductBeanReq resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                proList = resp.getProList();
                waresManage.getShopClassAsync(mProductClassCallback);
            } else {
                Slog.e("Failed update mProductClassCallback!!!!!!!  " + resp.getMessage());
            }
        }
    };

    private BaseCall<WaresManage.ListProductClassBeanReq> mProductClassCallback = new BaseCall<WaresManage.ListProductClassBeanReq>() {
        @Override
        public void call(WaresManage.ListProductClassBeanReq resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                classList = resp.getProclassList();
                handler.sendEmptyMessage(MSG_LOAD_PRODUCT_CLASS);
            } else {
                ToastUtils.showShort(mContext, "暂未添加数据");
                Slog.e("Failed update mProductClassCallback!!!!!!!  " + resp.getMessage());
            }
            dimessWaitingDialog();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_manage_shop_classify);
        waresManage = ReqFactory.buildInterface(this,
                WaresManage.class);
        findView();
        initData();
        initPopup();

        addCallback(mProductClassCallback);
        addCallback(mProductCallback);
    }

    private void findView() {
        View title = findViewById(R.id.vg_title);
        mTitle = new TitleView(this, title);
        mTitle.setCenterText(R.string.manage_product_all, null);
        mTitle = new TitleView(getApplicationContext(), title);
        mTitle.setLeftIcon(R.drawable.btn_back, this);
    }

    private void initData() {
        firstList = new ArrayList<>();
        //1
        ArrayList<ManageProductDetails> secondList1 = new ArrayList<>();

//        secondList1.add(new SecondClassItem(101, "自助餐"));
//        secondList1.add(new SecondClassItem(102, "西餐"));
//        secondList1.add(new SecondClassItem(103, "川菜"));
//        firstList.add(new FirstClassItem(1, "咖啡", handleTestingData()));
//        2
//        ArrayList<SecondClassItem> secondList3 = new ArrayList<SecondClassItem>();
//        secondList3.add(new SecondClassItem(301, "南开区"));
//        secondList3.add(new SecondClassItem(302, "和平区"));
//        secondList3.add(new SecondClassItem(303, "河西区"));
//        secondList3.add(new SecondClassItem(304, "河东区"));
//        secondList3.add(new SecondClassItem(305, "滨海新区"));
//        firstList.add(new FirstClassItem(2, "奶茶", handleTestingData()));
//        3
//        firstList.add(new FirstClassItem(3, "甜点", null));
//        4
//        firstList.add(new FirstClassItem(4, "咖啡", null));
        waresManage.getAllProductAsync(mProductCallback);
    }

    /**
     * default click event
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case TitleView.ID_LEFT:
                finish();
                break;
            case R.id.manage_btn_add:
                Intent intent = new Intent(this, ActivityManageAdd.class);
                Bundle bundle = new Bundle();
                bundle.putString("type", "pro_add");
                intent.putExtra("Message", bundle);
                startActivity(intent);
                break;
            case R.id.manage_btn_class:
                startActivity(new Intent(getApplicationContext(), ActivityManageProductClassify.class));
                break;
            case R.id.manage_btn_sort:
                break;
        }
    }

    class OnClickListenerImpl implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                default:
                    break;
            }
        }
    }

    private void initPopup() {
        leftLV = findViewById(R.id.pop_listview_left);
        rightLV = findViewById(R.id.pop_listview_right);
        manage_shop_rel = findViewById(R.id.manage_shop_rel);
        manage_btn_add = findViewById(R.id.manage_btn_add);
        manage_btn_class = findViewById(R.id.manage_btn_class);
        manage_btn_sort = findViewById(R.id.manage_btn_sort);
        manage_btn_add.setOnClickListener(this);
        manage_btn_class.setOnClickListener(this);
        manage_btn_sort.setOnClickListener(this);
        ViewGroup.LayoutParams lp;
        lp = manage_shop_rel.getLayoutParams();
        lp.width = ScreenUtils.getScreenW(this) * 2 / 3;
        lp.width = ScreenUtils.getScreenH(this);
        manage_shop_rel.setLayoutParams(lp);

        //为了方便扩展，这里的两个ListView均使用BaseAdapter.如果分类名称只显示一个字符串，建议改为ArrayAdapter.
        //加载一级分类
        firstAdapter = new FirstClassAdapter(this, firstList);
        leftLV.setAdapter(firstAdapter);

        //加载左侧第一行对应右侧二级分类
        secondList = new ArrayList<>();
//        secondList.addAll(firstList.get(0).getSecondList());
        secondAdapter = new ManageProductDetailsAdapter(this);
        secondAdapter.setData(secondList);
        rightLV.setAdapter(secondAdapter);

        secondAdapter.setCarriageManageListener(new CarriageManageListener() {
            @Override
            public void onCarriage(String productId, String shopId, boolean sale) {
                updateProductCarriage(shopId, productId, sale);
            }
        });

        //左侧ListView点击事件
        leftLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //二级数据
                List<ManageProductDetails> list2 = firstList.get(position).getSecondList();
                //如果没有二级类，则直接跳转
                if (list2 == null || list2.size() == 0) {
                    int firstId = firstList.get(position).getId();
                    String selectedName = firstList.get(position).getName();
                    handleResult(firstId, -1, selectedName);
                    return;
                }

                FirstClassAdapter adapter = (FirstClassAdapter) (parent.getAdapter());
                //如果上次点击的就是这一个item，则不进行任何操作
                if (adapter.getSelectedPosition() == position) {
                    return;
                }

                //根据左侧一级分类选中情况，更新背景色
                adapter.setSelectedPosition(position);
                adapter.notifyDataSetChanged();

                //显示右侧二级分类
                updateSecondListView(list2, secondAdapter);
            }
        });

        //右侧ListView点击事件
        rightLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //关闭popupWindow，显示用户选择的分类

                int firstPosition = firstAdapter.getSelectedPosition();
                int firstId = firstList.get(firstPosition).getId();
//                int secondId = firstList.get(firstPosition).getSecondList().get(position).getId();
//                String selectedName = firstList.get(firstPosition).getSecondList().get(position)
//                        .getName();
//                handleResult(firstId, secondId, selectedName);
            }
        });
    }

    //刷新右侧ListView
    private void updateSecondListView(List<ManageProductDetails> list2, ManageProductDetailsAdapter secondAdapter) {
        secondList.clear();
        secondList.addAll(list2);
        secondAdapter.notifyDataSetChanged();
    }

    //处理点击结果
    private void handleResult(int firstId, int secondId, String selectedName) {
//        String text = "first id:" + firstId + ",second id:" + secondId;
        Toast.makeText(this, "未添加数据", Toast.LENGTH_SHORT).show();
    }

    /**
     * debug 1 items list
     *
     * @return
     */
    private List<ManageProductDetails> handleTestingData() {
        List<ManageProductDetails> list = new ArrayList<>();
        ManageProductDetails manageProductDetails = new ManageProductDetails();
        manageProductDetails.setIvHead("");
        manageProductDetails.setProductName("奶茶奶绿");
        manageProductDetails.setProductSaleMoth("10");
        manageProductDetails.setProductStock("100");
        manageProductDetails.setPrice("15");
        list.add(manageProductDetails);
        return list;
    }

    /**
     * debug 1 items list
     *
     * @return
     */
    private List<ManageProductDetails> handleTestingData2() {
        List<ManageProductDetails> list = new ArrayList<>();
        ManageProductDetails manageProductDetails = new ManageProductDetails();
        manageProductDetails.setIvHead("");
        manageProductDetails.setProductName("奶茶奶绿");
        manageProductDetails.setProductSaleMoth("10");
        manageProductDetails.setProductStock("100");
        manageProductDetails.setPrice("15");
        list.add(manageProductDetails);
        list.add(manageProductDetails);
        list.add(manageProductDetails);
        list.add(manageProductDetails);
        return list;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (waresManage != null) {
            showWaitingDialog((ContextState) null);
            waresManage.getAllProductAsync(mProductCallback);
        }
    }

    /**
     * notify all data to ui
     * proList  product bean list
     * classList    product class list
     */
    private void notifyUi() {
        if (proList == null || proList.size() <= 0 || classList == null || classList.size() <= 0) {
            return;
        }
        firstList.clear();
        /* for ui display in first line */
        List<ManageProductDetails> initProductList = new ArrayList<>();
        /* clean first and second listview when load new view data */
        for (int i = 0; i < classList.size(); i++) {
            List<ManageProductDetails> productList = new ArrayList<>();
            productList.clear();
            for (int j = 0; j < proList.size(); j++) {
                ProductBean product = proList.get(j);
                if (classList.get(i).getProclassClassid() == product.getClassId()) {
                    ManageProductDetails bean = new ManageProductDetails();
                    bean.setPrice(product.getPrice());
                    bean.setProductSaleMoth(product.getMaxStock());
                    bean.setProductStock(product.getStock());
                    bean.setProductName(product.getName());
                    bean.setProductId(product.getProId());
                    bean.setClassId(product.getClassId());
                    bean.setIvHead(product.getThumbnail());
                    // we should be add on sale product to list
                    bean.setIsOnSale(product.getIsOnSale());
                    productList.add(bean);
                    if (i == 0) {
                        initProductList.add(bean);
                    }
                }
            }
            firstList.add(new FirstClassItem(i, classList.get(i).getProclassName(), productList));
            updateSecondListView(initProductList, secondAdapter);
        }
        firstAdapter.notifyDataSetChanged();
    }

    private void updateProductCarriage(String shopId, String productId, boolean sale) {
        String url = HttpConstant.setProductCarriage(null) + "?SHOP_ID=15651723391&PRODUCT_ID=" + productId + "&SALE=" + sale;
        final Request request = new Request.Builder().url(url).build();
        if (okHttpClient != null) {
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Slog.e("onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    parseProductString(body);
                    Slog.i("onResponse: " + body);
                }
            });
        }
    }

    private void parseProductString(String body) {
        //TODO do nothing
    }

    public interface CarriageManageListener {
        void onCarriage(String productId, String shopId, boolean sale);
    }
}

